/**
 * @param {number[][]} intervals
 * @return {number[][]}
 */
var merge = function (intervals) {
  if (intervals.length === 1) {
    return intervals;
  }

  intervals.sort((a, b) => a[0] - b[0]);

  for (let i = 0; i < intervals.length - 1; i++) {
    let newInterval = calculateInterval(intervals[i], intervals[i + 1]);
    if (newInterval.length > 0) {
      intervals.splice(i, 2, newInterval);
      i--;
    }
  }

  return intervals;
};

function calculateInterval(a, b) {
  const result = [];
  if (a[1] >= b[0]) {
    result.push(Math.min(a[0], b[0]), Math.max(a[1], b[1]));
  }

  return result;
}

// Example usage:
const intervals = [
  [1, 3],
  [2, 6],
  [8, 10],
  [15, 18],
];
console.log(merge(intervals));
